<template>
	<view class="c-image" :style="imgStyle">
		<image
			:class="['img', { load: loadStatus }]"
			:src="src"
			:mode="mode"
			@load="handleLoad"
			@error="handleError"
			@click="handlePreview"
		></image>
		<uni-transition :show="!loadStatus" :duration="300">
			<view class="icon-img" v-if="!loadStatus">
				<uni-icons type="image" size="28" color="#c0c4cc"></uni-icons>
			</view>
		</uni-transition>
	</view>
</template>

<script setup>
	/**
	 * 图片组件
	 * @description c-image 通用图片组件
	 * @property {String} src 资源路径
	 * @property {Boolean} isPreview=[true|false] 是否可以预览图片
	 * 	@value true 可以预览图片
	 * 	@value false 不可以预览图片
	 * @property {String|Number} width 图片宽
	 * @property {String|Number} height 图片高
	 * @property {String|Number} radius 图片圆角
 	 */
	import { computed, onMounted, reactive, toRefs } from 'vue';
	import _props from './props.js';
	import { handleUnit, previewImages } from '@/common/tools/index.js';

	const props = defineProps(_props);

	const state = reactive({
		loadStatus: false
	});

	const imgStyle = computed(() => {
		return {
			width: handleUnit(props.width),
			height: handleUnit(props.height),
			borderRadius: handleUnit(props.radius)
		};
	});

	const handleLoad = (e) => {
		state.loadStatus = true;
	};

	const handleError = (e) => {
		state.loadStatus = false;
	};

	const handlePreview = () => {
		if (props.isPreview) {
			previewImages([props.src]);
		}
	};

	const { loadStatus } = toRefs(state);
</script>

<style lang="scss">
	.c-image {
		position: relative;
		overflow: hidden;
		width: 120rpx;
		height: 120rpx;
		.img,
		.icon-img {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
		}
		.img {
			opacity: 0;
			transition: opacity 0.3s;
			&.load {
				opacity: 1;
			}
		}
		.icon-img {
			@include f-center($inline: inline-flex);
			background-color: $bg-color;
			border-radius: $radius-8;
		}
	}
</style>
